<?php
namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use \app\admin\model\Cats;
use \app\admin\model\Models;
use \app\admin\model\ModelField;
use \app\base\Tree;
use \app\admin\model\Syslog;


class Document extends Model
{
    use SoftDelete;
    protected $deleteTime = 'deltime';
    /*
        根据分类ID获得模型对像
    */
    static public function newObj($cid)
    {
        $class=Cats::get($cid);
        $model=Models::get($class['mid']);
        $modename=ucfirst($model['model_table']);
        $m="\\app\\admin\\model\\".$modename;
        if(!class_exists($m)){
            return false;
        }
        return new $m;
    }
    /*
        生成新建/修改表单
    */
    static public function build_form($cid,$act,$id)
    {
        $fields_list=array();
    	
        $class=Cats::get($cid);
        if(!$class){ return \Result(1,'没有找到分类信息'); }
        $model=Models::get($class['mid']);
        if(!$model){ return \Result(1,'没有找到模型信息'); }
        $fields=ModelField::where('mid',$class['mid'])->order('orderid ASC')->select();
        if(!$fields){ return \Result(1,'没有找到模型字段信息'); }

        $node_types=array('radio','checkbox','list');
        
        //可以直接输出数据的字段类型
        $types1=array('text','multi_text','float','single_image','multi_image','single_file',
        'single_media','single_ueditor','full_ueditor','baidu_map','color','hidden','orderid');
        
        $doc_count=db($model['model_table'])->count();
        $doc_count++;
        
        //编辑模式，加载相关数据
        if($act=='edit'){
            $doc=db($model['model_table'])->where("id",$id)->find();
            if(!is_array($doc)){
                return \Result(1,'没有找到文档信息');
            }
        }

        foreach($fields as $k=>$v){
            //解析选择数据节点
            if(in_array($v['field_type'],$node_types)){
                $data1=explode("\n",$v['field_data']);
                $d2=array();
                foreach($data1 as $key=>$val){
                    $dd=explode(":",$val);
                    if(isset($dd[0])and(isset($dd[1]))){
                        $kk=trim($dd[1]);
                        $vv=trim($dd[0]);
                        $d2[$key]['key']=$kk;
                        $d2[$key]['value']=$vv;
                        $d2[$key]['ischecked']="";
                        
                        //编辑模式，加载相关数据
                        if($act=='edit'){
                            $v['default_value']=$doc[$v['field_name']];
                        }else{
                            //非编辑模式加载默认数据
                            $v['default_value']=$v['default_value'];
                        }
                        
                        if(($v['field_type']=='radio' or $v['field_type']=='list') and $v['default_value']==$kk){
                            $d2[$key]['ischecked']="checked";
                        }else{
                            $d3=ClearNullArray(explode(',',$v['default_value']));
                            if(in_array($kk,$d3)){
                                $d2[$key]['ischecked']="checked";
                            }
                        }
                    }
                }
                $fields[$k]['node']=$d2;
            }else if(in_array($v['field_type'],$types1)){
                
                //编辑模式，加载相关数据
                if($act=='edit'){
                    $fields[$k]['value']=$doc[$v['field_name']];
                }else{
                    $fields[$k]['value']=$v['default_value'];
                }
            }else if($v['field_type']=='datetime'){
                //编辑模式，加载相关数据
                if($act=='edit'){
                    $fields[$k]['value']=MyDate('Y-m-d H:i:s',$doc[$v['field_name']]);
                }else{
                    $fields[$k]['value']=MyDate('Y-m-d H:i:s',time());
                }
            }else{
                $fields[$k]['value']="未知数据";
            }
            //加载主分类数据
            if($v['field_type']=='class'){
                $list=Cats::where('mid',$class['mid'])->order('orderid asc')->select();
                $tree=Tree::Create_Tree_Html($list,'parent','classname',0,0,'',$cid);
                $fields[$k]['node']=$tree;
            }
            $fields_list[]=$v['field_type'];
        }
        //统一两种编辑器标识符，方便前端只加载一次百度编辑器核心文件
        if(in_array('single_ueditor',$fields_list)or(in_array('full_ueditor',$fields_list))){
            $fields_list[]='ueditor';
        }
        $fields_list=array_unique($fields_list);

        $data=array(
            'fields'=>$fields,
            'fields_types'=>$fields_list,
            'page_title'=>($act=='edit'?'修改文档':'新建文档'),
            'doc_id'=>$id,
            'class'=>$class,
            'model_name'=>'document',
            'model_id'=>$class['mid'],
            'model_info'=>$model,
            'act'=>$act
        );
        return \Result(0,'获取成功',$data);
    }
    /*
        文档分页
    */
    static public function DocPage($cid,$kw,$kw_field,$page_size=30)
    {   
        $class=Cats::get($cid);
        if(!$class){ return \Result(1,'没有找到分类信息'); }
        $model=Models::get($class['mid']);
        if(!$model){ return \Result(1,'没有找到模型信息'); }
        $fields=ModelField::where('mid',$class['mid'])->where('list_show',0)->order('orderid ASC')->select();
        if(!$fields){ return \Result(1,'没有找到模型字段信息'); }
        
        //组装显示在列表中的字段
        $fields_lst=array();
        $fields_lst[]='id';
        $fields_title=array();
        $fields_key=array();
        foreach($fields as $k=>$v){
            $fields_lst[]=$v['field_name'];
            $fields_title[]=$v['field_title'];
            $fields_key[$v['field_name']]=$v;
        }
        
        //组装搜索的字段 
        $search_list=ModelField::field('field_name,field_title')->where("`mid`='".$class['mid']."' AND `search_type`=1")->select();
        $search_fields=array();
        $search_names=array();
        foreach($search_list as $v){
            $search_fields[]=$v['field_name'];
            $search_names[]=$v['field_title'];
        }
        $fields_str=implode(',',$fields_lst);
        //判断分类是否包含有分类字段
        $is_class=ModelField::where("`mid`='".$class['mid']."' AND `field_type`='class'")->find();
        //解析需要搜索的字段
        $kw_field_list=array_filter(explode(',',$kw_field));
        $kw_sql="";
        if($kw!=""){
            foreach($kw_field_list as $k=>$v){
                $kw_sql.=" (`$v` LIKE '%$kw%')";
                if(($k+1)<count($kw_field_list)){
                    $kw_sql.=" OR ";
                }
            }
        }
        //创建一个模型的模型
        $m=self::newObj($cid);
        //开始读取分页数据
        if($is_class){
            $class_name=$is_class['field_name'];
            $list=$m->field($fields_str)->where("(`parentstr` like '%,".$class['id'].",%' OR `$class_name`='".$class['id']."')")->where($kw_sql)->order('orderid DESC')->paginate($page_size, false, ['query' => request()->param()]);
        }else{
            $list=$m->field($fields_str)->where($kw_sql)->order('id DESC')->paginate($page_size, false, ['query' => request()->param()]);
        }
        $relst=array();
        //读取所有以分类ID为Key的所有分类列表
        $ClassList=self::GetALLCatsId();
        //显示数据预处理
        foreach($list as $rkey=>$row){
            $row=$row->toArray();
            $row_id=$row['id'];
            $relst[$row_id]['id']=$row_id;

            foreach($row as $fkey=>$field){
                if($fkey!="id"){
                    //获得字段类型
                    $F_Type=$fields_key[$fkey]['field_type'];
                    //获得字段数据用于解析单选、复选、列表
                    $F_Data=$fields_key[$fkey]['field_data'];
                    $relst[$row_id]['data'][$fkey]['type']=$F_Type;
                    if($F_Type=='class'){
                        //解析分类名称
                        $classname=$ClassList[$field]['classname']??'栏目已删除';
                        $relst[$row_id]['data'][$fkey]['value']=$classname;
                    }elseif($F_Type=='datetime'){
                        //解析时间数据
                        $relst[$row_id]['data'][$fkey]['value']=MyDate('Y-m-d H:i:s',$field);
                    }elseif($F_Type=='radio' || $F_Type=='list'){
                        //解析单选和列表数据
                        $lst=UnFieldData($F_Data);
                        $field=($field==""?0:$field);
                        $relst[$row_id]['data'][$fkey]['value']=$lst[$field];
                    }elseif($F_Type=='checkbox'){
                        //解析复选数据
                        $lst=UnFieldData($F_Data);
                        $vals=array_filter(explode(',',$field));
                        $arr=array();
                        foreach($vals as $sel){
                            $arr[]=$lst[$sel];
                        }
                        $relst[$row_id]['data'][$fkey]['value']=$arr;
                    }else{
                        $relst[$row_id]['data'][$fkey]['value']=$field;
                    }
                }else{
                    $relst[$row_id]['data'][$fkey]['type']='id';
                    $relst[$row_id]['data'][$fkey]['value']=$field;
                }
            }
        }

        $data= array(
            'kw'=>$kw,
            'search_names'=>implode(',',$search_names),
            'search_fields'=>implode(',',$search_fields),
            'fields_title'=>$fields_title,
            'list'=>$relst,
            'pagelist'=>$list->render(),
            'page_classid'=>$cid,
            'page_classname'=>$class['classname'],
            'page_title'=>$class['classname'].'-栏目信息管理',
            'model_name'=>$model['model_table']
        );
        return \Result(0,'获取成功',$data);
    }

    static public function GetALLCatsId()
    {
        $List=Cats::select();
        $ClassList=[];
    	foreach($List as $k=>$v){
    		$ClassList[$v['id']]=$v;
        }
        return $ClassList;     
    }    
    /*
        保存数据
    */
    static public function SaveData($data)
    {   
        $id=$data['id']??0;
        $doc_id=$data['doc_id']??0;

    	$mid=$data['model_id'];
    	$Insert_Array['mid']=$mid;
        //获得模型下的所有数据
    	$Model=Models::where('id',$mid)->find();
    	$Fields=ModelField::where('mid',$mid)->order('orderid ASC')->select();
    	//定义可以直接存储的字段类型
    	$Arr1=array('text','multi_text','float','radio','list','single_image',
    	'single_file','single_media','single_ueditor','full_ueditor','baidu_map','color','hidden','orderid');
    	//定义数组类型和多值的字段类型
    	$Arr2=array('checkbox','multi_image','multi_file','multi_media','area');
        
    	//根据系统预设字段来读取前端提交数据
    	foreach($Fields as $k=>$v){
 			//读取分类数据
 			if($v['field_type']=='class'){
 				if(isset($data[$v['field_name']]) and is_numeric($data[$v['field_name']])){
 					$classinfo=Cats::where('id',$data[$v['field_name']])->find();
 					$Insert_Array[$v['field_name']]=$data[$v['field_name']];
 					//处理分类路径数据
 					if(is_array($classinfo)){
 						$Insert_Array['parentstr']=$classinfo['path'];
 					}else{
 						$Insert_Array['parentstr']="";
 					}
 				}
 			}elseif(in_array($v['field_type'],$Arr1)){
 				//操作可以直接存储的字段
 				if(isset($data[$v['field_name']])){
 					$Insert_Array[$v['field_name']]=$data[$v['field_name']];
 				}else{
 					$Insert_Array[$v['field_name']]="";
 				}
 			}elseif(in_array($v['field_type'],$Arr2)){
 				//处理数组/多值类型的字段，然后用,号拼接在一起
 				if(isset($data[$v['field_name']])and(is_array($data[$v['field_name']]))){
 					$Insert_Array[$v['field_name']]=implode(',',$data[$v['field_name']]);
 				}else{
 					$Insert_Array[$v['field_name']]="";
 				}
 			}elseif($v['field_type']=='datetime'){
 				//处理时间类型的数据，并转换成UNIX时间缀
 				$Insert_Array[$v['field_name']]=GetMkTime($data[$v['field_name']]);
 			}
        }
        if(!isset($data['classid'])){
            return false;
        }
        $class=Cats::get($data['classid']);
        $Insert_Array['parentstr']=$class['path'];
        $m=self::newObj($data['classid']);
    	if($data['doc_id']>=1){
            Syslog::Rec(1,"更新了".$Model['model_name'].'模型的文档:'.$data['doc_id'],0);
    		return $m->where('id',$data['doc_id'])->update($Insert_Array);
    	}else{
            Syslog::Rec(1,"创建了".$Model['model_name'].'模型的文档',0);
    		return $m->insert($Insert_Array);
        }
    }
    /*
        排序
    */
    static public function Sort($data)
    {
        $m=self::newObj($data['classid_sel']);

        foreach($data['field_ids'] as $k=>$v){
            $list[]=['id'=>$v,'orderid'=>$data['orderid_ipt'][$k]];
        }
        if($m->isUpdate()->saveAll($list)){
            Syslog::Rec(1,"更新了模型的文档排序",0);
            return \Result(0,'操作成功');
        }else{
            return \Result(1,'操作失败');
        }
    }
    /*
        批量操作(删除、启用、禁用、...)
    */
    static public function Bat($data)
    {
        $type='bat_'.$data['type'];
        $m=self::newObj($data['excid']);
        $ids=\implode(',',array_unique(array_filter(\explode(',',$data['ids']))));
        return self::$type($m,$ids);
    }
    /*
        批量启用 status:0 启用 1:禁用
    */
    static public function bat_enable($obj,$ids)
    {
        Syslog::Rec(1,"批量启用了模型的文档[$ids]",0);
        return $obj->where("`id` IN ($ids)")->update(['status'=>0]);
    }
    /*
        批量禁用 status:0 启用 1:禁用
    */
    static public function bat_disable($obj,$ids)
    {
        Syslog::Rec(1,"批量禁用了模型的文档[$ids]",0);
        return $obj->where("`id` IN ($ids)")->update(['status'=>1]);
    }
    /*
        批量删除
    */
    static public function bat_del($obj,$ids)
    {
        Syslog::Rec(1,"批量删除了模型的文档[$ids]",0);
        return $obj->destroy($ids);
    }
}